package com.wodan.zhongjinjicang.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.wodan.zhongjinjicang.common.utils.FtpUtil;
import com.wodan.zhongjinjicang.common.utils.IDUtils;
import com.wodan.zhongjinjicang.common.utils.JavaSmsApi;
import com.wodan.zhongjinjicang.common.utils.VerificationCode;
import com.wodan.zhongjinjicang.enums.ResponseCodeEnum;
import com.wodan.zhongjinjicang.enums.YesOrNoEnum;
import com.wodan.zhongjinjicang.mapper.VerificationMapper;
import com.wodan.zhongjinjicang.model.ResponseResult;
import com.wodan.zhongjinjicang.model.UserBean;
import com.wodan.zhongjinjicang.model.VerificationBean;
import com.wodan.zhongjinjicang.service.PictureService;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

@Service
public class PictureServiceImpl implements PictureService {
	
	@Autowired 
    private VerificationMapper verificationDao;

	@Value("${FTP_ADDRESS}")
	private String FTP_ADDRESS;
	@Value("${FTP_PORT}")
	private Integer FTP_PORT;
	@Value("${FTP_USERNAME}")
	private String FTP_USERNAME;
	@Value("${FTP_PASSWORD}")
	private String FTP_PASSWORD;
	@Value("${FTP_BASE_PATH}")
	private String FTP_BASE_PATH;
	@Value("${IMAGE_BASE_URL}")
	private String IMAGE_BASE_URL;
	
	@Override
	public ResponseResult uploadPicture(MultipartFile uploadFile) {

		try {
			//生成一个新的文件名
			//取原始文件名
			String oldName = uploadFile.getOriginalFilename();
			//生成新文件名
			//UUID.randomUUID();
			String newName = IDUtils.genImageName();
			newName = newName + oldName.substring(oldName.lastIndexOf("."));
			//图片上传
			String imagePath = new DateTime().toString("/yyyy/MM/dd");
			boolean result = FtpUtil.uploadFile(FTP_ADDRESS, FTP_PORT, FTP_USERNAME, FTP_PASSWORD,
					FTP_BASE_PATH, imagePath, newName, uploadFile.getInputStream());
			//返回结果
			if(!result) {
				return ResponseResult.build(ResponseCodeEnum.FAIL.getCode(), "文件上传失败");
			}
			Map<String , Object> modelMap = new HashMap<String , Object>();
			modelMap.put("face", IMAGE_BASE_URL + imagePath + "/" + newName);
			return ResponseResult.build(ResponseCodeEnum.FAIL.getCode(), "文件上传成功",modelMap);

		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

}
